//
//  ViewController.swift
//  GeoCoding
//
//  Created by xmg on 16/8/21.
//  Copyright © 2016年 wlis. All rights reserved.
//

import UIKit
import CoreLocation
class ViewController: UIViewController {

    @IBOutlet weak var addressText: UITextView!
    
    
    @IBOutlet weak var latitudeText: UITextField!
    
    @IBOutlet weak var longitudeText: UITextField!
    
    private lazy var geocoder : CLGeocoder = CLGeocoder()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }


}


extension ViewController {

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        view.endEditing(true)
    }

    @IBAction func geoCodeBtn(sender: AnyObject) {
    
        /** 获取用户输入的地址名称 */
        guard let address = addressText.text else {return}
        
        geocoder.geocodeAddressString(address) { (placemark :[CLPlacemark]?, error :NSError?) -> Void in
            /** 错误校验 */
            if error != nil {return}
            /** 对结果进行校验 */
            guard let placemarks = placemark else{return}
            for place in placemarks {
                print(place.name);
                /** 获取地理位置 */
                guard let location = place.location else { continue }
                
                /** 获取经纬度 */
                let latitude = location.coordinate.latitude
                let longitude = location.coordinate.longitude
                
                /** 将经纬显示 */
                self.latitudeText.text = "\(latitude)"
                self.longitudeText.text = "\(longitude)"
                
            }
        }
    
    }
    
    @IBAction func reverseBtn(sender: AnyObject) {
    
        /** 获取用户输入的经纬度 */
        guard let latitude = latitudeText.text else { return}
        guard let longitude = longitudeText.text else { return}
        
        guard let latitudeD = Double(latitude) else {return}
        guard let longitudeD = Double(longitude) else {return}
        
        let location = CLLocation(latitude: latitudeD, longitude: longitudeD)
        /** 反地理编码 */
        geocoder.reverseGeocodeLocation(location) { (placemark:[CLPlacemark]?, error : NSError?) -> Void in
            /** 校验错误 */
            if error != nil {return}
            /** 校验结果 */
            guard let placemark = placemark else { return}
            
            /** 遍历结果 */
            for place in placemark {
                guard let addressDict = place.addressDictionary else{continue}
                guard let addressArray = addressDict["FormattedAddressLines"] as? [String] else{continue}
                guard let address = addressArray.last else {continue}
                
                self.addressText.text = address
            }
        }
    
    }
}
